var currentpage = 1, totalpage = 10, pagesize = 10;
$(function () {
	callfetsetcoursefun("#publishedCourse")
	//切换标签时查询课程
	$('#courselistcan a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
		//防太过频繁切换标签，发送过多请求
		if (previouspage.nowtime && $(e.target.hash).find("span.glyphicon").length && (Date.now() - previouspage.nowtime < 2000)) {
			adjustHeight();
			return;
		}
		previouspage.nowtime = Date.now();
		$('#partpagenavbar').fadeOut();
		$('#container>img[alt="loading"]').fadeIn(100);
		currentpage = 1;
		var divid = e.target.getAttribute("href");
		callfetsetcoursefun(divid);
	});
});
//调用getset发布、未发布课程方法
function callfetsetcoursefun(divid) {
	var queryLessones = function (type) {
		var sucessfct = function (data) {
			currentpage = data.currentPageNo;
			totalpage = data.totalPageCount;
			pagesize = data.pagesize;
			setCourseContext(data.result, divid);
		};
		$.ajax({
			url: "publishlessons/queryresult",
			type: "POST",
			contentType: "application/json",
			data: JSON.stringify({
				owner: UserID,
				pageindex: currentpage,
				pagesize: pagesize,
				modeid: type
			}),
			dataType: "json",
			success: sucessfct,
			error: function (event) {
				window.parent.parentLayermsg(langThis("role_optionfaild"));
				$('#container>img[alt="loading"]').fadeOut();
				// console.log(event);
			}
		});
	};
	switch (divid) {
		case "#publishedCourse": queryLessones(7); break;//查询设置正在进行的课程
		case "#unpublishedCourse": queryLessones(1); break;// 查询设置待审核课程
		case "#onEditingCourse": getsetonEditingCourse(divid); break;// 查询设置待发布课程
		case "#outdatedCourse": queryLessones(6); break;// 查询设置过时课程
	}
}
// 查询设置待发布课程
function getsetonEditingCourse(divid) {
	var sucessfct = function (data) {
		currentpage = data.currentPageNo;
		totalpage = data.totalPageCount;
		pagesize = data.pagesize;
		setCourseContext(data.result, divid);
	};
	$.ajax({
		url: "lessons/queryresult",
		type: "POST",
		contentType: "application/json",
		data: JSON.stringify({
			owner: UserID,
			pageindex: currentpage,
			pagesize: pagesize
		}),
		dataType: "json",
		success: sucessfct,
		error: function (event) {
			window.parent.parentLayermsg(langThis("role_optionfaild"));
			$('#container>img[alt="loading"]').fadeOut();
			// console.log(event);
		}
	});
}
//适应高度
function adjustHeight() {
	// 子页面设置父页面iframe高度
	if (window.parent.setiframeHeight) {
		var ht = $("#container").height();
		ht = ht > 800 ? ht : 800;
		window.parent.setiframeHeight(ht);
	}
	$('#container>img[alt="loading"]').fadeOut();
}
//填充内容
function setCourseContext(data, divid) {
	if (!data.length) {
		$(divid).html('<div class="askcreatcourse"><p><a target="_blank" href="./cOmCourse" ><span class="glyphicon glyphicon-plus" aria-hidden="true"></span>' + langThis("kc_creat_course") + '</a></p></div>');
		$('#partpagenavbar').fadeOut();
		adjustHeight();
		return;
	}
	var context = '<ul class="media-list">';
	for (var i in data) {
		context += '<li class="media lessonbottomHr" data-lessonid="' + data[i].id + '" data-phase="' + data[i].phase + '">';
		context += '<a class="media-left" target="_blank" href="./lessonDetail?lid=' + data[i].id + '&p=' + data[i].phase + '">';
		context += '<img style="cursor:pointer;" src="' + data[i].image + '"  class="lessonimg"></a>';
		context += '<div class="media-body"><h3 class="media-heading lessonTitle">' + data[i].name + '</h3>';
		context += '<p class="lessontxt">' + data[i].description + '</p>';
		// 按钮们
		//课程详情
		context += '<a title="' + langThis("ms_lessDetail") + '" type="button" class="btn btn-primary" target="_blank" href="./lessonDetail?lid=' + data[i].id + '&p=' + (!data[i].phase ? 0 : data[i].phase) + '"><span class="glyphicon glyphicon-th-list"></span></a>';
		switch (divid) {
			//进行中
			case "#publishedCourse": {
				//招生信息
				context += '<a title="' + langThis("ms_recruitstmg") + '" type="button" class="btn btn-warning" target="_blank" href="./recruit?lid=' + data[i].id + '&p=' + data[i].phase + '"><span class="glyphicon glyphicon-book"></span></a>';
				//成绩评定
				// context += '<a title="' + langThis("master_labcorrecting") + '" type="button" class="btn btn-info" target="_blank" href="./CSCorrecting?lid=' + data[i].id + '&p=' + data[i].phase + '"><span class="glyphicon glyphicon-stats"></span></a>';
				//复制课程
				// context += '<a title="' + langThis("mc_copycourse") + '" type="button" class="btn btn-success" onclick="copycourse(' + data[i].id + ',\'' + divid + '\')"><span class="glyphicon glyphicon-file"></span></a>';
			} break;
			// 待审核
			case "#unpublishedCourse": {
				//撤回审核
				context += '<a title="' + langThis("rm_retreatRecruit") + '" type="button" class="btn btn-warning" onclick="retreatCourse(' + data[i].id + ',' + data[i].phase + ',\'' + divid + '\')"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="14" height="14" viewBox="4 5 16 14" fill="#fff"><path d="M10,9V5L3,12L10,19V14.9C15,14.9 18.5,16.5 21,20C20,15 17,10 10,9Z" /></svg></a>';
			} break;
			// 待发布
			case "#onEditingCourse": {
				//修改课程
				context += '<a title="' + langThis("kc_modify_course") + '" type="button" class="btn btn-info" target="_blank" href="./cOmCourse?lid=' + data[i].id + '"><span class="glyphicon glyphicon-edit"></span></a>';
				//复制课程
				context += '<a title="' + langThis("mc_copycourse") + '" type="button" class="btn btn-success" onclick="copycourse(' + data[i].id + ',\'' + divid + '\')"><span class="glyphicon glyphicon-file"></span></a>';
				//删除课程
				context += '<a title="' + langThis("mc_deletecourse") + '" type="button" class="btn btn-danger" onclick="deletecourse(' + data[i].id + ',\'' + divid + '\')"><span class="glyphicon glyphicon-trash"></span></a>';
				//发布课程
				context += '<a title="' + langThis("mc_publishcoursebtn") + '" type="button" class="btn btn-warning" onclick="publishCourse(' + data[i].id + ',\'' + divid + '\')"><span class="glyphicon glyphicon glyphicon-send"></span></a>';
			} break;
			// 已结束
			case "#outdatedCourse": {
				//学生信息
				context += '<a title="' + langThis("rt_recruitlist") + '" type="button" class="btn btn-warning" target="_blank" href="./recruit?lid=' + data[i].id + '&p=' + data[i].phase + '"><span class="glyphicon glyphicon-book"></span></a>';
				//成绩评定
				// context += '<a title="' + langThis("master_labcorrecting") + '" type="button" class="btn btn-info" target="_blank" href="./CSCorrecting?lid=' + data[i].id + '&p=' + data[i].phase + '"><span class="glyphicon glyphicon-stats"></span></a>';
				//复制课程
				// context += '<a title="' + langThis("mc_copycourse") + '" type="button" class="btn btn-success" onclick="copycourse(' + data[i].id + ',\'' + divid + '\')"><span class="glyphicon glyphicon-file"></span></a>';
			} break;
		}

		//开课批次，待发布和1不显示
		var phaseString = "";
		if (data[i].phase && data[i].phase != 1) {
			phaseString = '<span class="badge lessonSstag">' + langThis("cm_coursePhase").replace("{p}", data[i].phase) + '</span> ';
		}
		//课程类型
		context += '<span class="classPhaseSpan">' + phaseString + ' <span class="badge lessonTypeTag">' + (/zh/.test(getCurrentLang()) ? data[i].typenamecn : data[i].typenameen) + '</span></span>';
	}
	context += '</ul>';
	$(divid).html(context);
	$('#partpagenavbar').fadeIn();
	setpartpagebar(divid);
	adjustHeight();
}
// 复制课程
function copycourse(lsid, divid) {
	var title = {};
	title.text = "<span class='glyphicon glyphicon-info-sign'></span>&nbsp;" + langThis("mc_layerConfirmTitle");
	title.css = {
		'color': "#fff",
		'background-color': '#5cb85c',
		'font-weight': 'bold'
	};
	var masg = langThis("mc_copycourseConfirm");
	var btn1 = langThis("kc_confirm");
	var btn2 = langThis("pm_cancle");
	var fun1 = function () {
		//服务
		$.ajax({
			url: "lessons/" + lsid + "/copy",
			type: "POST",
			// data:"",
			dataType: "json",
			contentType: "application/json",
			success: function (data) {
				window.parent.parentCloseAll();
				callfetsetcoursefun(divid);
			},
			error: function (event) {
				window.parent.parentCloseAll();
				window.parent.parentLayermsg(langThis("role_optionfaild"));
				// console.log(event);
			}
		});
	};
	window.parent.parentLayerConfirm(title, masg, btn1, btn2, fun1);
}
//删除课程
function deletecourse(lsid, divid) {
	var title = {};
	title.text = "<span class='glyphicon glyphicon-exclamation-sign'></span>&nbsp;" + langThis("pm_delete");
	title.css = {
		'color': "#fff",
		'background-color': '#d9534f',
		'font-weight': 'bold'
	};
	var masg = langThis("kc_delete");
	var btn1 = langThis("kc_confirm");
	var btn2 = langThis("pm_cancle");
	var fun1 = function () {
		window.parent.parentLoading();
		//服务
		$.ajax({
			url: "lessons/" + lsid,
			type: "DELETE",
			contentType: "application/json",
			success: function (data) {
				window.parent.parentCloseAll();
				window.parent.parentLayermsg(langThis("mi_OprationSucess"), { icon: 1 });
				callfetsetcoursefun(divid);
			},
			error: function (event) {
				window.parent.parentCloseAll();
				window.parent.parentLayermsg(langThis("role_optionfaild"), { icon: 2 });
			}
		});
	};
	window.parent.parentLayerConfirm(title, masg, btn1, btn2, fun1);
}
//撤回审核
function retreatCourse(lsid, ps, divid) {
	var title = {};
	title.text = "<span class='glyphicon glyphicon-question-sign'></span>&nbsp;" + langThis("rm_retreatRecruit");
	title.css = {
		'color': "#fff",
		'background-color': '#f0ad4e',
		'font-weight': 'bold'
	};
	var masg = langThis("rm_retreatRecruit_qu");
	var btn1 = langThis("kc_confirm");
	var btn2 = langThis("pm_cancle");
	var fun1 = function () {
		//服务
		$.ajax({
			url: "publishlessons/" + lsid + "/" + ps + "/changemode",
			type: "POST",
			contentType: "application/json",
			data: JSON.stringify({
				"modeid": 7
			}),
			dataType: "json",
			success: function (data) {
				window.parent.parentCloseAll();
				callfetsetcoursefun(divid);
			},
			error: function (event) {
				window.parent.parentCloseAll();
				window.parent.parentLayermsg(langThis("role_optionfaild"));
				// console.log(event);
			}
		});
	};
	window.parent.parentLayerConfirm(title, masg, btn1, btn2, fun1);
}
//发布课程
function publishCourse(lsid, divid) {
	var title = {};
	title.text = "<span class='glyphicon glyphicon-question-sign'></span>&nbsp;" + langThis("cs_setchooseEndDate");
	title.css = {
		'color': "#fff",
		'background-color': '#3071a9',
		'font-weight': 'bold'
	};
	var masg = '<input id="DatePicker" class="layui-input" style="width: 100%;" placeholder="' + langThis("cs_chooseDate") + '" onclick="layui.laydate({elem:this,min:laydate.now(0),max: laydate.now(+365),format:\'YYYY-MM-DD\',festival:true})">';
	var btn1 = langThis("mc_publishcoursebtn");
	var btn2 = langThis("pm_cancle");
	var fun1 = function () {
		var enddate = window.parent.document.getElementById("DatePicker").value.trim();
		if (!enddate) {
			return;
		}
		window.parent.parentLoading();
		$.ajax({
			url: "lessons/" + lsid + "/publish",
			type: "POST",
			contentType: "application/json",
			data: JSON.stringify({ "enddate": enddate }),
			dataType: "json",
			success: function (data) {
				window.parent.parentCloseAll();
				window.parent.parentLayermsg(langThis("mi_OprationSucess"), { icon: 1 });
				// callfetsetcoursefun(divid);
			},
			error: function (event) {
				window.parent.parentCloseAll();
				window.parent.parentLayermsg(langThis("role_optionfaild"), { icon: 2 });
			}
		});
	};
	window.parent.parentLayerConfirm(title, masg, btn1, btn2, fun1);
}
//分页控制
function setpartpagebar(divid) {
	var pagesli = '';
	//首页、上一页
	if (currentpage == 1 || totalpage == 1) {
		pagesli += '<li title="' + langThis("nav_master") + '" class="active"><a>&laquo;</a></li>';
		pagesli += '<li title="' + langThis("nav_pre") + '" class="active"><a>&lt;</a></li>';
	} else {
		pagesli += '<li title="' + langThis("nav_master") + '"><a style="cursor:pointer;" onclick="gotofirstpage(\'' + divid + '\')">&laquo;</a></li>';
		pagesli += '<li title="' + langThis("nav_pre") + '"><a style="cursor:pointer;" onclick="previouspage(\'' + divid + '\')">&lt;</a></li>';
	}
	//页码
	var startpage;
	if (currentpage - 5 <= 0) {
		startpage = 1;
	} else if (currentpage + 5 > totalpage) {
		startpage = totalpage - 9;
	} else {
		startpage = currentpage - 4;
	}
	// 左过长
	if (startpage > 1) {
		pagesli += '<li><a style="cursor:pointer;" onclick="gotopage(\'' + divid + '\',' + (startpage - 1) + ')">...</a></li>';
	} else {
		startpage = 1;
	}
	for (var j = startpage; j <= totalpage; j++) {
		if (j == currentpage) {
			pagesli += '<li class="active"><a>' + j + '</a></li>';
		} else {
			pagesli += '<li><a style="cursor:pointer;" onclick="gotopage(\'' + divid + '\',' + j + ')">' + j + '</a></li>';
		}
		//右过长
		if ((j == startpage + 9) && (j < totalpage)) {
			pagesli += '<li><a style="cursor:pointer;" onclick="gotopage(\'' + divid + '\',' + (startpage + 10) + ')">...</a></li>';
			break;
		}
	}
	//下一页、尾页
	if (currentpage == totalpage || totalpage == 1) {
		pagesli += '<li title="' + langThis("nav_next") + '" class="active"><a>&gt;</a></li>';
		pagesli += '<li title="' + langThis("nav_last") + '" class="active"><a>&raquo;</a></li>';
	} else {
		pagesli += '<li title="' + langThis("nav_next") + '"><a style="cursor:pointer;" onclick="nextpage(\'' + divid + '\')">&gt;</a></li>';
		pagesli += '<li title="' + langThis("nav_last") + '"><a style="cursor:pointer;" onclick="gotolastpage(\'' + divid + '\')">&raquo;</a></li>';
	}
	$("#partpagenavbar>ul.pagination").html(pagesli);
	$("#partpagenavbar").fadeIn();
}
function previouspage(divid) {
	currentpage--;
	callfetsetcoursefun(divid);
}
function nextpage(divid) {
	currentpage++;
	callfetsetcoursefun(divid);
}
function gotopage(divid, pagenum) {
	currentpage = pagenum;
	callfetsetcoursefun(divid);
}
function gotofirstpage(divid) {
	currentpage = 1;
	callfetsetcoursefun(divid);
}
function gotolastpage(divid) {
	currentpage = totalpage;
	callfetsetcoursefun(divid);
}
// 翻页快捷键
document.onkeydown = function (e) {
	var divid = $("#courselistcan>ul>li.active>a").attr("href");
	if ((e || event).keyCode == 37 && currentpage > 1) {//上一页
		previouspage(divid);
	} else if ((e || event).keyCode == 39 && currentpage < totalpage) {//下一页
		nextpage(divid);
	} else if ((e || event).keyCode == 36 && currentpage != 1) {//首页
		gotofirstpage(divid);
	} else if ((e || event).keyCode == 35 && currentpage != totalpage) {//尾页
		gotolastpage(divid);
	}
};